import router from '@/router'
import setting from './setting'
// @ts-expect-error
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
nprogress.configure({ showSpinner: false })

// 获取用户相关的小仓库内部token数据,去判断用户是否登录成功
import { useUserStore } from './stores/modules/user'
//

export function setupPermission(pinia) {
  const userStore = useUserStore(pinia)

  // 全局前置守卫
  router.beforeEach(async (to, from, next) => {
    document.title = `${setting.title} - ${to.meta.title}`
    nprogress.start()
    const token = userStore?.user?.data || null
    const name = userStore?.userinfo?.name || null

    if (token) {
      if (to.path === '/login') {
        next({ path: '/' })
      } else {
        if (name) {
          next()
        } else {
          await userStore.delUser()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    } else {
      if (to.path === '/login') {
        next()
      } else {
        next({ path: '/login', query: { redirect: to.path } })
      }
    }
  })

  // 全局后置守卫
  router.afterEach(() => {
    nprogress.done()
  })
}
